using System;
using System.Collections.Generic;
using CosyTrade.Core;
using CosyTrade.Data;
using CosyTrade.Store;
using NHibernate.Expression;

namespace CosyTrade
{
    [Addin("ProductManager")]
    public class ProductManager : AddinBase, IProductManager
    {
        public void CreateProduct(Product product)
        {
            OrmDataAccess.Create(product);
        }

        public void UpdateProduct(Product product)
        {
            OrmDataAccess.Save(product);
        }

        public bool CanDeleteProduct(Guid productKey)
        {
            IList<CompanyStore> store = OrmDataAccess.FindAll<CompanyStore>(Expression.Eq("Product.PrimaryKey", productKey));
            return store.Count == 0;
        }

        public void DeleteProduct(Guid productKey)
        {
            OrmDataAccess.Delete(GetProductDetail(productKey));
        }

        public Product GetProductDetail(Guid productKey)
        {
            return OrmDataAccess.FindByPrimaryKey<Product>(productKey);
        }

        public void CreateProductCategory(ProductCategory category)
        {
            OrmDataAccess.Create(category);
        }

        public void UpdateProductCategory(ProductCategory category)
        {
            OrmDataAccess.Save(category);
        }

        public bool CanDeleteProductCategory(Guid categoryKey)
        {
            IList<ProductCategory> subLst = GetProductSubList(categoryKey);
            if (subLst.Count == 0)
            {
                IList<Product> proLst = GetProductList(categoryKey);
                return proLst.Count == 0;
            }
            return false;
        }

        public void DeleteProductCategory(Guid categoryKey)
        {
            OrmDataAccess.Delete(GetProductDetail(categoryKey));
        }

        public ProductCategory GetProductCategoryDetail(Guid primaryKey)
        {
            return OrmDataAccess.FindByPrimaryKey<ProductCategory>(primaryKey);
        }

        public IList<ProductCategory> GetProductRootList()
        {
            return OrmDataAccess.FindAll<ProductCategory>(Expression.Eq("IsRootCategory", true));
        }

        public IList<ProductCategory> GetProductSubList(Guid parentKey)
        {
            return OrmDataAccess.FindAll<ProductCategory>(Expression.Eq("ParentCategoryBase.PrimaryKey", parentKey));
        }

        public IList<Product> GetProductList(Guid categoryKey)
        {
            return OrmDataAccess.FindAll<Product>(Expression.Eq("Category.PrimaryKey", categoryKey));
        }

        public IList<Product> SearchProductList(ICriterion criterion, int maxReturnCount, params Order[] orderBy)
        {
            return OrmDataAccess.SlicedFindAll<Product>(0, maxReturnCount, orderBy, criterion);
        }
    }
}